<?php declare(strict_types=1);

namespace App\Http\Controller;

use ReflectionException;
use Swoft;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Context\Context;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Response;
use App\Http\Middleware\ControllerMiddleware;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;

use Swoft\Http\Server\Annotation\Mapping\Middleware;
use Swoft\Http\Server\Annotation\Mapping\Middlewares;

use Swoft\View\Renderer;
use Swoft\Db\DB;
use App\Model\Entity\Tags;
use App\Model\Logic\Qa;
use App\Model\Logic\SiteMap as Map;
use Throwable;
use Swoft\Http\Message\Request;

use Thepixeldeveloper\Sitemap\Urlset;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;
use Thepixeldeveloper\Sitemap\SitemapIndex;
use Thepixeldeveloper\Sitemap\Sitemap;
use Thepixeldeveloper\Sitemap\Extensions\Mobile;
use Swoft\Log\Helper\CLog;
/**
 * Class HomeController
 * @Controller(prefix="/")
 * @Middlewares({
 * @Middleware(ControllerMiddleware::class)
 * })
 */
class HomeController
{
    /**
     * @RequestMapping("/")
     * @throws Throwable
     */
    public function index(): Response
    {
        $data = Tags::orderByRaw('rand()')->limit(50)->offset(0)->pluck('name', 'id')->toArray();
        return view('home/index', ['data' => $data, 'site' => Context::get()->getRequest()->site_info]);
    }

    /**
     * @RequestMapping(route="/tag/{id}[/{page}]")
     * @param int $id
     * @param int $page
     * @return Response
     * @throws Throwable
     */
    public function tag(int $id, int $page = 1): Response
    {
        $tag               = Tags::where('id', $id)->value('name');
        $data              = Qa::withTag($id, $page);
        $data['tag_list']      = Tags::where('name', 'like', '%' . $tag . '%')->where('id', '<>', $id)->limit(30)->pluck('name', 'id');
        $data['site']      = Context::get()->getRequest()->site_info;
        $data['url']       = '/tag/' . $id . '/';
        $data['current']   = $page;
	$data['title']       = implode(',', array_values(array_slice($data['data']['tag_list'], 0, 5))) . $data['site']['keywords'];
        $data['keywords']    = $data['title'];
        $data['description'] = $data['site']['description'];
	CLog::info(json_encode($data,320));
        return view('home/search', $data);
    }

    /**
     * @RequestMapping(route="/a/{question_id}")
     * @param string $question_id
     * @return Response
     * @throws Throwable
     */
    public function detail(string $question_id)
    {
        $ext      = substr($question_id, 1, 3);
        $question = DB::table('question' . $ext)->where('question_id', $question_id)->first();
        //TODO 判断问题不存在跳转

        $question_content = DB::table('question' . $ext . '_content')->where('question_id', $question_id)->value('question');
        $question_comment = DB::table('question' . $ext . '_comment')->where('question_id', $question_id)->value('comment');
        $answer           = DB::table('question' . $ext . '_answer')->where('question_id', $question_id)->orderByRaw('flag DESC,answer_id ASC')->get(['answer', 'user', 'created_at', 'answer_id'])->toArray();
        $answer_comment   = [];

        $tags = Tags::whereIn('id', explode(',', $question['tags']))->pluck('name', 'id')->toArray();
        if (count($tags) < 10) {
            $tag  = Tags::orderByRaw('rand()')->limit(9)->pluck('name', 'id')->toArray();
            $tags = array_merge(array_flip($tags), array_flip($tag));
        }

        if ($answer) {
            $answer_comment = DB::table('question' . $ext . '_answer_comment')->whereIn('answer_id', array_column($answer, 'answer_id'))->pluck('comment', 'answer_id')->toArray();
        }

        $data = [
            'question'         => $question,
            'question_content' => $question_content,
            'question_comment' => $question_comment,
            'answer'           => $answer,
            'answer_comment'   => $answer_comment,
            'site'             => Context::get()->getRequest()->site_info,
            'tags'             => array_flip($tags)
        ];

        return view('home/detail', $data);
    }

    /**
     * @RequestMapping(route="/search[/{keywords}/{page}]")
     * @param string $keywords
     * @param int $page
     * @return Response
     * @throws Throwable
     */
    public function search(string $keywords, int $page)
    {
        $request  = Context::get()->getRequest();
        $keywords = empty($keywords) ? $request->get('keywords', 'python') : $keywords;
        $page     = empty($page) ? $request->get('page', 1) : $page;
        $data     = Qa::search($keywords, (int)$page);

        $data['site']     = $request->site_info;
        $data['url']      = '/search/' . $keywords . '/';
        $data['current']  = $page;
	$data['title']       = implode(',', array_values(array_slice($data['data']['tag_list'], 0, 5))) . $data['site']['keywords'];
	$data['word']        = $keywords;
        $data['keywords']    = $keywords . ',' . $data['title'];
        $data['description'] = $data['site']['description'];
	CLog::info(json_encode($data,320));
        return view('home/search', $data);
    }

    /**
     * @RequestMapping(route="/makesitemap")
     * @param Request $request
     * @return Response
     * @throws Swoft\Exception\SwoftException
     */
    public function makeSiteMap(Request $request): Response
    {
        $base_path = dirname(__DIR__) . '/../../public' . DIRECTORY_SEPARATOR;
        $sitemap   = $base_path . 'sitemap.xml';
        $link      = 'https://' . $request->getUri()->getHost();
        try {
            if (!is_file($sitemap)) {
                Map::make($sitemap, $link);
            }
            Map::sitemapIndex($link, $base_path);
            return context()->getResponse()->withStatus(200)->withContent('SUCCESS');
        } catch (\Exception $e) {
            return context()->getResponse()->withStatus(403)->withContent($e->getMessage());
        }
    }
}
